package org.gbif.agi.webapp.action;

import com.opensymphony.xwork2.Preparable;
import org.appfuse.service.GenericManager;
import org.gbif.agi.model.AGIDatasource;
import org.appfuse.webapp.action.BaseAction;

import java.util.List;

public class AGIDatasourceAction extends BaseAction implements Preparable {
    private GenericManager<AGIDatasource, Long> aGIDatasourceManager;
    private List aGIDatasources;
    private AGIDatasource aGIDatasource;
    private Long  id;

    public void setAGIDatasourceManager(GenericManager<AGIDatasource, Long> aGIDatasourceManager) {
        this.aGIDatasourceManager = aGIDatasourceManager;
    }

    public List getAGIDatasources() {
        return aGIDatasources;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String aGIDatasourceId = getRequest().getParameter("aGIDatasource.id");
            if (aGIDatasourceId != null && !aGIDatasourceId.equals("")) {
                aGIDatasource = aGIDatasourceManager.get(new Long(aGIDatasourceId));
            }
        }
    }

    public String list() {
        aGIDatasources = aGIDatasourceManager.getAll();
        return SUCCESS;
    }

    public void setId(Long  id) {
        this. id =  id;
    }

    public AGIDatasource getAGIDatasource() {
        return aGIDatasource;
    }

    public void setAGIDatasource(AGIDatasource aGIDatasource) {
        this.aGIDatasource = aGIDatasource;
    }

    public String delete() {
        aGIDatasourceManager.remove(aGIDatasource.getId());
        saveMessage(getText("aGIDatasource.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            aGIDatasource = aGIDatasourceManager.get(id);
        } else {
            aGIDatasource = new AGIDatasource();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (aGIDatasource.getId() == null);

        aGIDatasourceManager.save(aGIDatasource);

        String key = (isNew) ? "aGIDatasource.added" : "aGIDatasource.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}